package com.litong.spring.mvc.listener;

import java.lang.management.ManagementFactory;
import java.util.Set;

import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.Query;
import javax.management.QueryExp;

public class TomcatUtils {

  public static int getTomcatPort() throws MalformedObjectNameException, NullPointerException {
    // 获取beanServer
    MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
    // <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1"
    // redirectPort="8443"/>
    QueryExp match = Query.match(Query.attr("protocol"), Query.value("HTTP/1.1"));
    ObjectName objectName = new ObjectName("*:type=Connector,*");
    Set<ObjectName> objectNames = beanServer.queryNames(objectName, match);
    // 获取port标签的值
    String port = objectNames.iterator().next().getKeyProperty("port");
    return Integer.valueOf(port);
  }
}